package com.gateway.server.common.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gateway.server.common.constant.Constant;
import com.gateway.server.common.response.CommonResponse;
import com.gateway.server.common.util.StringUtils;
import com.gateway.server.modules.feignServiceApi.AuthApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/**
 * 描述: AuthFilter token 全局鉴权过滤器
 * <p>
 * 作者: hu_to
 * 时间: 2020/02/27 16:12
 */
public class AuthFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    @Autowired
    private AuthApiService authApiService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = request.getHeaders();
        URI uri = request.getURI();
        // 过滤出不需要权限验证的uri
        if (uri.getPath().contains("login") || uri.getPath().contains("logout")
                || uri.getPath().contains("/api/rest/file/") || uri.getPath().contains("/img/")) {
            return chain.filter(exchange);
        }
        List<String> authorizations = headers.get("Authorization");
        if (authorizations != null && StringUtils.isNotBlank(authorizations.get(0))) {
            String authorization = authorizations.get(0);
            logger.info("authorization:::{}", authorization);
            // 进行token校验
            CommonResponse commonResponse = authApiService.validToken(authorization);
            if (Constant.Permission.SUCCESS == Integer.parseInt(commonResponse.get("code").toString())) {
                return chain.filter(exchange);
            } else {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        } else {
            String token = request.getQueryParams().getFirst("token");
            logger.info("token:::{}", token);
            if (token == null || token.isEmpty()) {
                // 封装错误信息
                try {
                    // 将信息转换为 JSON
                    ObjectMapper objectMapper = new ObjectMapper();
                    byte[] data = objectMapper.writeValueAsBytes(CommonResponse.error(401, "Token is empty"));

                    // 输出错误信息到页面
                    DataBuffer buffer = response.bufferFactory().wrap(data);
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                    return response.writeWith(Mono.just(buffer));
                } catch (JsonProcessingException e) {
                    logger.error("解析json数据格式异常", e);
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
